<template>
    <div class="w-[85vw] py-4 px-8 overflow-auto">
        <!-- 个人信息部分 -->
        <h1 class="text-xl font-bold mb-4">个人信息</h1>
        <div class="grid grid-cols-2 gap-4 mb-4">
            <div class="flex items-center space-x-4 p-4">
                <div>姓名</div>
                <var-input variant="outlined" v-model="tempForm.name" disabled size="small" class="bg-white w-[30%]" />
            </div>
            <div class="flex items-center space-x-4 p-4">
                <div>性别</div>
                <var-input v-if="user.sex" variant="outlined" v-model="user.sex" disabled size="small" class="bg-white w-[30%]" />
                <var-select v-else variant="outlined" size="small" focus-color="#006263" class="bg-white w-[30%]" v-model="tempForm.sex">
                    <var-option label="男" value="MAN" />
                    <var-option label="女" value="WOMAN" />
                </var-select>
            </div>
            <div class="flex items-center space-x-4 p-4">
                <div>身份</div>
                <var-input variant="outlined" v-model="user.identity" disabled size="small" class="bg-white w-[30%]" />
            </div>
            <div class="flex items-center space-x-4 p-4">
                <div>科室</div>
                <var-input v-if="user.departmentId" variant="outlined" v-model="user.departmentName" disabled size="small" class="bg-white w-[30%]" />
                <var-select v-if="!user.departmentId" v-model="tempForm.departmentName" clearable variant="outlined" size="small" focus-color="#006263" class="bg-white w-[60%]" @change="isDepartmentSelected = !!tempForm.departmentId">
                    <var-option v-for="dept in departments" :key="dept.departmentId" :label="dept.departmentName" :value="dept.departmentId" />
                </var-select>
                <var-input v-if="!user.departmentId" v-show="!isDepartmentSelected" v-model="tempDepartmentInput" focus-color="#006263" variant="outlined" placeholder="输入科室" size="small" class="bg-white w-[25%]" @keyup.enter="checkDepartment" />
            </div>
            <div class="flex items-center space-x-4 py-4 px-8">
                <var-button v-if="!user.departmentId" variant="contained" color="#006263" text-color="#FFFFFF" @click="showAddDepartment = true">添加科室</var-button>
            </div>
        </div>
        <!-- 联系方式部分 -->
        <h1 class="text-xl font-bold mb-4">联系方式</h1>
        <div class="grid grid-cols-2 gap-4 mb-4 h-[72px]">
            <div class="flex items-center space-x-4 px-4">
                <div>邮箱</div>
                <var-input variant="outlined" v-model="tempForm.email" focus-color="#006263" size="small" class="bg-white" style="width: 20vw" :rules="emailRules" />
            </div>
            <div class="flex items-center space-x-4 px-4">
                <div>手机号</div>
                <var-input variant="outlined" v-model="tempForm.phone" focus-color="#006263" size="small" class="bg-white" style="width: 20vw" :rules="phoneRules" />
            </div>
        </div>
        <!-- 账号安全部分 -->
        <h1 class="text-xl font-bold mb-4">账号安全</h1>
        <div class="grid grid-cols-2 gap-4 mb-4 h-[72px]">
            <div class="flex items-center space-x-4 px-4">
                <div>更改密码</div>
                <var-input variant="outlined" v-model="tempForm.password" clearable focus-color="#006263" size="small" class="bg-white" style="width: 18vw" :rules="passwordRules" />
            </div>
        </div>
        <!-- 身份凭证部分 -->
        <div class="flex items-center">
            <h1 class="text-xl font-bold mb-2">身份凭证</h1>
            <img class="w-[30px] mb-2 mx-[2vw]" :class="{ spin: isAgain }" src="@/assets/重新生成.svg" @click="getUserInfo" />
        </div>
        <div class="grid grid-cols-2 gap-4">
            <div class="flex items-center space-x-4 h-[90px]">
                <var-uploader v-if="user.authenticationFlag == 0 || user.authenticationFlag == 3" v-model="file" :maxlength="1" type="file" :maxsize="1000000" accept="image/*" style="width: 30%" @click-action="checkBeforeUpload">
                    <var-button variant="contained" color="#006263" text-color="#FFFFFF">上传医师执业证书</var-button>
                </var-uploader>
                <var-alert v-if="user.authenticationFlag == 0" type="danger" title="用户信息未验证" />
                <var-alert v-if="user.authenticationFlag == 1" type="success" title="用户信息已验证" />
                <var-alert v-if="user.authenticationFlag == 2" type="warning" title="用户信息审批中" />
                <var-alert v-if="user.authenticationFlag == 3" type="danger" title="用户信息验证失败，请重新上传医师执业证书！" />
            </div>
            <div class="flex items-center space-x-4 h-[90px]">
                <div class="w-[40%]"></div>
                <var-button variant="contained" color="#006263" text-color="#FFFFFF" size="large" @click="show = true">上传更改后的信息</var-button>
            </div>
        </div>
        <var-dialog v-model:show="show" title="是否提交更改" confirm-button-text-color="#006263" cancel-button-text-color="#006263" @before-close="editInfo">
            <var-loading description="LOADING" color="#006263" :loading="loading">个人信息确认后不允许再更改</var-loading>
        </var-dialog>
        <var-dialog v-model:show="showAddDepartment" title="添加科室" confirm-button-text-color="#006263" persistent cancel-button-text-color="#006263" width="30vw" @before-close="handleBeforeClose">
            <var-loading description="LOADING" color="#006263" :loading="loading">
                <p class="text-sm p-4 text-[#666]">注意，新建成功后将自动成为改科室主任，请谨慎操作！</p>
                <div class="p-4">
                    <var-input v-model="newDepartment" variant="outlined" placeholder="请输入科室名称（格式：xx医院xx科室）" focus-color="#006263" size="small" :rules="departmentRules" />
                </div>
            </var-loading>
        </var-dialog>
    </div>
</template>

<script>
export default {
    name: 'App',
    data() {
        return {
            tempForm: {},
            file: [],
            show: false,
            showAddDepartment: false,
            departments: [],
            isAgain: false,
            newDepartment: '',
            tempDepartmentInput: '', // 临时输入的科室
            isDepartmentSelected: false, // 用于控制输入框的显示
            loading: false
        };
    },
    computed: {
        user() {
            return this.$store.user;
        },
        emailRules() {
            return [(v) => !!v || '邮箱不能为空', (v) => /.+@.+\..+/.test(v) || '邮箱格式不正确'];
        },
        phoneRules() {
            return [(v) => !!v || '手机号不能为空', (v) => /^\d{11}$/.test(v) || '手机号格式不正确'];
        },
        passwordRules() {
            return [(v) => !!v || '密码不能为空', (v) => v.length >= 6 || '密码长度必须大于等于6'];
        },
        departmentRules() {
            return [(v) => !!v || '科室名称不能为空', (v) => /^.+医院.+科室$/.test(v) || '格式不正确，请输入 xx医院xx科室'];
        }
    },
    watch: {
        // 监听 tempForm.department 的值变化
        'tempForm.departmentId'(newVal) {
            this.isDepartmentSelected = !!newVal;
        }
    },
    async created() {
        // 初始化临时表单数据
        this.tempForm = { ...this.user };
        if (!this.user.departmentId) {
            await this.getDeptList();
        }
    },
    methods: {
        checkBeforeUpload(chooseFile) {
            if (this.tempForm.name && this.tempForm.sex && this.tempForm.departmentName) {
                chooseFile();
            } else {
                this.$api.notify.error('数据不完整，请先完善个人信息！');
            }
        },
        async handleBeforeClose(action, done) {
            if (action === 'confirm') {
                if (!this.newDepartment) {
                    this.$api.notify.error('科室名称不能为空！');
                    return;
                }
                this.loading = true;
                const res = await this.$api.department.addDepartment({ departmentName: this.newDepartment });
                if (res.success) {
                    this.loading = false;
                    this.showAddDepartment = false;
                    this.$api.notify.success('科室创建成功！');
                    this.$store.user.updateMyInfo();
                    this.tempForm = { ...this.user };
                    this.newDepartment = '';
                } else {
                    this.loading = false;
                    this.$api.notify.error(res.error);
                }
            } else {
                done();
            }
        },
        async getUserInfo() {
            this.isAgain = true;
            await this.$store.user.updateMyInfo();
            this.isAgain = false;
        },
        async getDeptList() {
            const res = await this.$api.department.getDeptList();
            if (res.success) {
                this.departments = res.data;
            } else {
                this.$api.notify.error(res.error);
            }
        },
        checkDepartment() {
            this.tempForm.departmentName = this.tempDepartmentInput;
            const departmentName = this.tempForm.departmentName;
            const found = this.departments.some((dept) => dept.departmentName === departmentName);
            if (!found) {
                this.$api.notify.error('该科室不存在！');
                this.tempForm.departmentName = '';
            }
        },
        async editInfo(action, done) {
            if (action === 'confirm') {
                if (!this.tempForm.email || !this.tempForm.phone || !this.tempForm.password) {
                    this.$api.notify.error('邮箱、手机号、密码不能为空！');
                    this.show = false;
                    return;
                }
                this.loading = true;
                const keys = ['name', 'sex', 'departmentName', 'email', 'phone', 'password'];
                let isModified = false;
                let isupdateUserInfo = false;
                // 检查是否有字段被修改
                for (const key of keys) {
                    if (this.user[key] !== this.tempForm[key]) {
                        isModified = true;
                        break;
                    }
                }
                if (!isModified && this.file.length === 0) {
                    this.loading = false;
                    this.show = false;
                    this.$api.notify.error('信息未修改！');
                    return;
                }
                if (this.tempForm.password.includes('*') && this.tempForm.password !== '*********') {
                    this.loading = false;
                    this.show = false;
                    this.$api.notify.error('密码不能包含*字符！');
                    return;
                }
                // 生成只包含被修改字段的更新数据
                const updateData = Object.fromEntries(
                    Object.entries(this.tempForm)
                        .filter(([key, value]) => {
                            return this.user[key] !== value;
                        })
                        .map(([key, value]) => {
                            // 如果是 department 字段，将其键名改为 department_id
                            if (key === 'departmentName') {
                                return ['departmentId', value];
                            }
                            return [key, value];
                        })
                );
                // 如果有文件上传，则上传文件
                if (this.file.length > 0) {
                    const rawFile = this.file[0]?.file || toRaw(this.file[0]);
                    const formData = new FormData();
                    formData.append('files', rawFile);
                    const res = await this.$api.user.uploadImg(formData);
                    if (res.success) {
                        isupdateUserInfo = true;
                    }
                }
                // 调用后端接口更新用户信息
                if (Object.keys(updateData).length > 0) {
                    const res = await this.$api.user.updateUserInfo(updateData);
                    if (res.success) {
                        isupdateUserInfo = true;
                    }
                }
                if (isupdateUserInfo) {
                    await this.$store.user.updateMyInfo();
                    this.loading = false;
                    this.show = false;
                } else {
                    done();
                }
            }
        }
    }
};
</script>
<style scoped>
.spin {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>
